package org.java.api.service.impl;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.java.api.service.SendEmailService;
import org.java.api.utils.RandomCode;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author WHQ
 * @version 1.0
 * @date 2022-3-11 0011 下午 2:36
 */
@Service
@Api(tags = "监听邮件消息队列的服务层")
public class SendEmailServiceImpl implements SendEmailService {
    @Value("${spring.mail.username}")
    private String from;
    @Value("${email.code.prefix}")
    private String prefix;
    //注入发送邮件的模板
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @RabbitListener(queues = "send-queue")
    @ApiOperation(value = "接收邮件队列发送过来的邮件，同时发送邮件到用户的邮箱")
    @Override
    public void listenerTo(String to) {
        System.out.println("需要发送到:"+to);
        //得到随机验证码
        String code = RandomCode.getCode();
        //拼接成需要发送的邮件
        String msg=RandomCode.INFORMATION+code;
        SimpleMailMessage mailMessage=new SimpleMailMessage();
        //设置标题
        mailMessage.setSubject("注册验证码");
        //设置主题信息
        mailMessage.setText(msg);
        //设置发件人
        mailMessage.setFrom(from);
        //设置发给谁
        mailMessage.setTo(to);
        //开始发送
        mailSender.send(mailMessage);
        //拼接redis key
        String key=prefix+to;
        //发送成功，将随机验证码存放到redis缓存，过期时间三分钟
        stringRedisTemplate.boundValueOps(key).set(code);
        //过期时间三分钟
        stringRedisTemplate.expire(key,3, TimeUnit.MINUTES);
        System.out.println("邮件发送成功");
    }
}
